/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fait.ferm.ui;

import fait.ferm.ui.tables.FeedPersonalRow;
import fait.ferm.datafx.TableViewFactory;
import fait.ferm.global.Glob;
import fait.ferm.persists.Cow;
import fait.ferm.persists.Cow_group;
import fait.ferm.persists.Directory;
import fait.ferm.persists.SimpleDirItem;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.Accordion;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBuilder;
import javafx.scene.control.Label;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.TextFieldBuilder;
import javafx.scene.control.TitledPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.GridPaneBuilder;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;


/**
 *
 * @author alex
 */
public class PlanTabFeedingPaneController implements Initializable{
	
	@FXML
	private Accordion everyDayAcc;
	@FXML
	private TitledPane forAll;
	@FXML
	private Button addBt;
	@FXML
	private Button editBt;
	@FXML
	private Button delBt;
	@FXML
	private HBox tabBox;
//	@FXML
//	private TableView<FeedPersonalRow> persTable;
//	@FXML
//	private TableColumn<FeedPersonalRow, Cow> cow1;
//	@FXML
//	private TableColumn<FeedPersonalRow, Boolean> isGroup2;
//	@FXML
//	private TableColumn<FeedPersonalRow, SimpleDirItem> sup3;
//	@FXML
//	private TableColumn<FeedPersonalRow, Double> quantity4;
//	@FXML
//	private TableColumn<FeedPersonalRow, String> begDate5;
//	@FXML
//	private TableColumn<FeedPersonalRow, String> endDate6;
	
	private TableView<FeedPersonalRow>  persTable;
	private ObservableList<FeedPersonalRow> persItems = FXCollections.observableArrayList();
//	private TableView<Gtest>  persTable;
//	private ObservableList<Gtest> persItems = FXCollections.observableArrayList();
	
	
	
	private HashMap<Integer, TextField> forAllTextFieldMap; 
	private ObjectProperty<FeedPersonalRow> personalRow;
	private int persSelIndex;

	public static FeedPersonalRow CUR_PERS_ROW;
	public static boolean IS_NEW;
	
	/**
	 * Initializes the controller class.
	 * 
	 * @param url 
	 * @param rb 
	 */
	@Override
	public void initialize(URL url, ResourceBundle rb) {
		personalRow = new SimpleObjectProperty<>();
		forAllTextFieldMap = new HashMap<>();
		fillEveryDay();
		try {
			//bindPersTableCol();
			createPersTableCol();
		} catch (Exception ex) {
			Logger.getLogger(PlanTabFeedingPaneController.class.getName()).log(Level.SEVERE, null, ex);
		}
		addListeners();	
	}			
	
	private void fillEveryDay(){
		ArrayList<Cow_group> arrCowGroup = (ArrayList<Cow_group>)Glob.getFermEngine().getCowGroup().obj;
		forAll.contentProperty().set(createGrid(true));
		for( Cow_group cg: arrCowGroup ){
			everyDayAcc.getPanes().add( 
					new TitledPane( cg.cow_type.getName()+" "+cg.date_purchase.toString(), createGrid(false))
			);		
		}
	}
	
	private GridPane createGrid(boolean forAll){
		Directory d = Glob.getDirInCache("supplies");
		GridPane gp = GridPaneBuilder.create()
				.alignment(Pos.TOP_LEFT)
				.hgap(10)
				.vgap(10)
				.padding(new Insets(10, 10, 10, 10))
				.build();
		int r=0;
		for(SimpleDirItem x: d.getItems()){
			gp.add(new Label(x.getName()) , 0, r);
			TextField tf = TextFieldBuilder.create()
					.text("0")
					.prefWidth(120)
					.userData(x)
					.alignment(Pos.CENTER_RIGHT)
					.build();
			if(forAll){ forAllTextFieldMap.put(x.getId(), tf);}
			gp.add(tf, 1, r);
			r++;
		}
		if(forAll){
			gp.add( ButtonBuilder.create()
					.maxWidth(Double.MAX_VALUE)
					.text("Применить ко всем")
						.onAction(new EventHandler<ActionEvent>() {
							@Override public void handle(ActionEvent t) {
								everyDayApplyForAll();
							}
						})
					.build(), 
					0,r,2,1);
		}
		return gp;
	}
	
	private void everyDayApplyForAll(){
		for(TitledPane tp: everyDayAcc.getPanes()){
			if(tp == forAll){ continue;}
			GridPane gp = (GridPane) tp.getContent();
			for(Node nx:gp.getChildren()){
				if(nx.getClass().getName().equals("javafx.scene.control.TextField") ){
					TextField tf = (TextField) nx;
					SimpleDirItem sd = (SimpleDirItem) tf.getUserData();
					tf.textProperty().set( forAllTextFieldMap.get(sd.getId()).getText());
				}
			}
		}
	}
	
	@FXML
	private void addDialog() {
	try {
		persSelIndex = -1;
		IS_NEW = true;
		FXMLLoader fl = new FXMLLoader();
		BorderPane p = (BorderPane) fl.load(getClass().getResource("PlanTabFeedingDialogPane.fxml").openStream());
		PlanTabFeedingDialogPaneController c = fl.getController();
		c.returnedValue = 	personalRow;
		Glob.dialogPane.centerProperty().set(p);
		Glob.dialogPane.toFront();
	} catch (IOException ex) {
		Logger.getLogger(CreditTabController.class.getName()).log(Level.SEVERE, null, ex);
	}
    }

	@FXML
	private void editDialog() {
	try {
		persSelIndex = persTable.getSelectionModel().getSelectedIndex();
		CUR_PERS_ROW = persTable.getSelectionModel().getSelectedItem();
		IS_NEW = false;
		FXMLLoader fl = new FXMLLoader(getClass().getResource("PlanTabFeedingDialogPane.fxml"));
		BorderPane p = (BorderPane) fl.load();
		PlanTabFeedingDialogPaneController c = fl.getController();
		c.returnedValue = 	personalRow;
		Glob.dialogPane.centerProperty().set(p);
		Glob.dialogPane.toFront();
	} catch (IOException ex) {
		Logger.getLogger(CreditTabController.class.getName()).log(Level.SEVERE, null, ex);
	}
			for(FeedPersonalRow x: persTable.getItems())
			System.out.println(""+x.toString());

    }
	
	
	@FXML
	private void deleteBtnClick() {
		FeedPersonalRow r = persTable.getSelectionModel().getSelectedItem();
		persItems.remove(r);
		persTable.setItems(persItems);
    }
	
	private void addListeners(){
		//изменение выбранной коровы
		personalRow.addListener(new ChangeListener<FeedPersonalRow>(){
			@Override
			public void changed(ObservableValue<? extends FeedPersonalRow> ov, FeedPersonalRow oldVal, FeedPersonalRow newVal) {
				if(newVal!=null){
					//если такой записи в таб нет, 
					if( persSelIndex >= 0 ){
					//изменяем зн
						persItems.set(persSelIndex, newVal);
					}else{
					//добавляем в таблицу
						persItems.add(newVal);
					}
					persTable.setItems(persItems);
				}
			}		
		});
	}

	private void createPersTableCol() throws Exception{
		Directory d = Glob.getDirInCache("supplies");
		persItems.add(new FeedPersonalRow(new Cow(1), true, d.get(1), 10, new Date(), new Date()));
		persItems.add(new FeedPersonalRow(new Cow(2), false, d.get(2), 20, new Date(), new Date()));
		persItems.add(new FeedPersonalRow(new Cow(3), true, d.get(3), 30, new Date(), new Date()));
		
		persTable = TableViewFactory.create(FeedPersonalRow.class, persItems).buildTableView();
//		persTable.setEditable(false);
//		persTable.getColumns().get(3).setEditable(false);
		
		
		
		tabBox.getChildren().add(persTable);
		HBox.setHgrow(persTable, Priority.ALWAYS); 
	}
}

